<?php
/**
 * Created by PhpStorm.
 * User: edmmss
 * Date: 2018/11/13
 * Time: 09:15
 */

namespace app\modules\pool;


class WorkerPool implements \Countable
{
    private $_occupiedWorkers = [];

    private $_freeWorkers = [];

    /**
     * 获取对象池对象
     *
     * @date   2018/11/14
     * @author edmmss
     * @return StringReverseWorker
     */
    public function get(): StringReverseWorker
    {
        if (count($this->_freeWorkers) == 0) {
            $worker = new StringReverseWorker();
        } else {
            $worker = array_pop($this->_freeWorkers);
        }

        $this->_occupiedWorkers[spl_object_hash($worker)] = $worker;

        return $worker;
    }

    /**
     * 将对象回收到对象池，而不是销毁
     *
     * @date   2018/11/14
     * @author edmmss
     * @param StringReverseWorker $worker
     */
    public function dispose(StringReverseWorker $worker)
    {
        $objectHash = spl_object_hash($worker);

        if (isset($this->_occupiedWorkers[$objectHash])) {
            unset($this->_occupiedWorkers[$objectHash]);
            $this->_freeWorkers[$objectHash] = $worker;
        }
    }

    public function count(): int
    {
        // TODO: Implement count() method.
        return count($this->_occupiedWorkers) + count($this->_freeWorkers);
    }
}